package com.juyu.miliao.api.util;

import com.alibaba.fastjson.JSON;
import com.juyu.miliao.common.domain.GaodeConfig;
import com.juyu.miliao.common.util.OkHttpUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * http工具类
 *
 * @author xuanqicheng
 */
public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final int outTime = 5000;
    private static final int socketTimeOut = 5000;

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * @param url
     * @return
     * @throws IOException
     */
    public static String httpGetUtil(String url){

        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeOut)
                .setConnectTimeout(outTime).build();

        HttpGet get = new HttpGet(url);

        get.setConfig(requestConfig);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            CloseableHttpResponse response = httpClient.execute(get);
            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回响应体的内容
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            logger.error("http请求错误：" + e.getMessage());
        }
        return null;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        logger.info("doGet请求连接："+url+"|请求参数"+ JSON.toJSONString(map));

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {

                String  value = "";
                if(StringUtils.isNotBlank(entry.getKey())){
                    if(entry.getValue()!=null){
                        value = entry.getValue().toString();
                    }

                    uriBuilder.setParameter(entry.getKey(), value);
                }

            }
        }

        // 调用不带参数的get请求
        return  HttpUtil.httpGetUtil(uriBuilder.build().toString());
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("key", "2dc23d5dbc02de8c0419ad9ffa2af753");
        map.put("ip", "115.231.107.72");
        String paramString = OkHttpUtil.combineGetParms(map);
        String url = GaodeConfig.IP_URL + paramString;
        String string =HttpUtil.httpGetUtil(url);
        System.out.println(string);
    }
}
